package com.xtsoft.platform.task.service;

import com.xtsoft.platform.globe.enums.AgentStr;
import com.xtsoft.platform.globe.enums.YesNo;

import com.xtsoft.platform.task.domain.CommonTask;
import com.xtsoft.platform.task.domain.SchedulerTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.xtsoft.core.common.Constants;
import com.xtsoft.core.utils.ResultMsg;


//import com.xtsoft.base.task.SnmpTask;

//改了yesno

/**
 * 
 * @ClassName:  TaskManager   
 * @Description: 任务调度管理
 * @author: defencez
 * @date:   2018年10月24日 上午11:18:28
 */
@Service
public class TaskManager {

	private final static Logger logger = LoggerFactory.getLogger(TaskManager.class);
	
	@Autowired
	private SchedulerTaskService schedulerTaskService;
	
	@Autowired
	private TaskSchedulersService taskSchedulerService;
	
	@Transactional
	public ResultMsg startOrStop(String taskId){
		SchedulerTask schedulerTask = schedulerTaskService.get(taskId);
		String msg = "";
		if(null == schedulerTask)
			return new ResultMsg(false,"无法获取该任务，可能任务已被删除");
		
		Class  ct = null;
		CommonTask commonTask = null;
		ResultMsg result = new ResultMsg();
		
		try {
			ct = Class.forName(schedulerTask.getClassName()); 
			commonTask = (CommonTask)ct.newInstance();
		}catch(Exception e) {
			logger.error(e.getLocalizedMessage());
			result.setSuccess(false);
			result.setMsg("调度任务时出现错误：" + e.getLocalizedMessage());
			return result;
		}
				
		commonTask.setTaskId(taskId);
		commonTask.setTaskName(schedulerTask.getName());
		commonTask.setCron(schedulerTask.getCron());
		//commonTask.setCron(CronUtil.getCronExpression(busTask.getPeriodType(), busTask.getPeriod()));
				
		if(schedulerTask.getState() == YesNo.Yes.getIntValue()) {
			taskSchedulerService.stopTask(commonTask);
			result.setSuccess(true);
			result.setMsg(schedulerTask.getName() + "任务成功停止!");
			schedulerTask.setState(YesNo.No.getIntValue());
			schedulerTaskService.save(schedulerTask);
		}else {
			msg = taskSchedulerService.startTask(commonTask);
			if(msg.equals(AgentStr.Rep_StartDeviceFault.getDes())) {
				result.setSuccess(false);
				result.setMsg(schedulerTask.getName() + "任务启动失败!");
			}
			if(msg.equals(AgentStr.Rep_StartDeviceSuccess.getDes())) {
				result.setSuccess(true);
				result.setMsg(schedulerTask.getName() + "任务启动成功!");
				schedulerTask.setState(YesNo.Yes.getIntValue());
				schedulerTaskService.save(schedulerTask);
			}			
		}
		return result;
	}
}
